﻿using System;                                                                    
using System.Data;                                                               
using System.Web.UI;
using System.Web.UI.WebControls;
using Subgurim.Controles;
using System.Drawing;
using NetCard;
using NetCard.Controllers;
using System.Collections.Generic;
using NetCard.Models;
using System.Web.SessionState;
using System.Web.Mvc;
using NetCard.Dao;

namespace NetCard
{

    public class MapIndex : ViewPage<NetCard.Models.Project>
    {
        public GMap GMap1;
        private RouterController routerCtrl = new RouterController();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.LoadMap();

                long id = (long)Session["project"];
                Session["curProjectId"] = id;
                this.Context.Session.Add("project1", id);
                this.Context.Session.Timeout = 20;

                ProjectController projectCtrl = new ProjectController();
                ProjectDao projectDao = new ProjectDao();
                Project project = projectDao.GetProject(id);

                GMap1.setCenter(new GLatLng((int)project.x, (int)project.y), (int)project.zoom);


                List<Router> routerList = new List<Router>();
                RouterController routerCtrl = new RouterController();

                RouterDao routerDao = new RouterDao();
                routerList = routerDao.GetRouters(id);

                foreach (Router router in routerList)
                {
                    GMarkerOptions mkrOpts = new GMarkerOptions();
                    mkrOpts.draggable = true;

                    GIcon icon = new GIcon();

                    if (router.status == null)
                    {
                        icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
                    }
                    else
                    {
                        if (router.status.Equals("online    "))
                        {
                            icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
                        }
                        else
                        {
                            icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
                        }
                    }

                    mkrOpts.icon = icon;

                    double x = Decimal.ToDouble((decimal)router.y);
                    double y = Decimal.ToDouble((decimal)router.x);
                    GLatLng point = new GLatLng(x, y);
                    GMarker marker = new GMarker(point, mkrOpts);

                    string markerId = marker.ID;

                    GInfoWindow window = new GInfoWindow(marker,
                        string.Format(@"
                    <a href=Router/RouterTest>Проверить<a><br/>
                    <a href=Router/AllRoutersTest>Проверить всё<a><br/><br/>
                    <a href=Router/RouterDelete>Удалить</a><br/>
                    <a href=Router/RouterEdit>Редактировать</a>")
                        // сразу отображаем
                    , false
                    , GListener.Event.click
                    );
                    GMap1.addInfoWindow(window);



                    GMap1.addListener(new GListener(marker.ID, GListener.Event.dragend,
                    string.Format(@"
           function(overlay, point)
           {{
              var ev = new serverEvent('myDragEnd', {0});
              ev.addArg({0}.getZoom());
              ev.addArg(this.getPoint());
              ev.send();
           }}
           ", GMap1.GMap_Id)));

                    GMap1.addListener(new GListener(marker.ID, GListener.Event.dragstart,
                    string.Format(@"
           function(overlay, point)
           {{
              var event = new serverEvent('start', {0});
              event.addArg({0}.getZoom());
              event.addArg(this.getPoint());
              event.send();
           }}
           ", GMap1.GMap_Id)));


                    GMap1.addListener(new GListener(marker.ID, GListener.Event.click,
                        string.Format(@"
           function(overlay, point)
           {{
              var event = new serverEvent('click', {0});
              event.addArg({0}.getZoom());
              event.addArg(this.getPoint());
              event.send();
           }}
           ", GMap1.GMap_Id)));

                }
            

            }
            catch
            {
            }
        }



        protected string GMap1_ServerEvent(object s, GAjaxServerEventOtherArgs e)
        {
            try
            {
                string js = string.Empty;

                switch (e.eventName)
                {
                    case "start":
                        {
                            GLatLng myPoint = GAjaxServerEventArgs.latlngFromString(e.eventArgs[1]);
                            Session["point"] = myPoint;
                        }
                        break;

                    case "click":
                        GLatLng myPoint1 = GAjaxServerEventArgs.latlngFromString(e.eventArgs[1]);
                        Session["point"] = myPoint1;
                        break;

                    case "myDragEnd":

                        string markerId = GMap1.getGMapElementById(e.who);
                        string zoomLevel = e.eventArgs[0];
                        GLatLng endPoint = GAjaxServerEventArgs.latlngFromString(e.eventArgs[1]);

                        GLatLng startPoint = (GLatLng)Session["point"];

                        RouterDao routerDao = new RouterDao();
                        Router router = routerDao.GetRouterByXY(Decimal.Parse(startPoint.lng.ToString()),
                                                                 Decimal.Parse(startPoint.lat.ToString()));
                        router.x = Decimal.Parse(endPoint.lng.ToString());
                        router.y = Decimal.Parse(endPoint.lat.ToString());
                        routerCtrl.RouterMove(router);

                        break;
                }
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }


        private void LoadMap()
        {
            GMap1.Height = 600;
            GMap1.Width = 800;
            GMap1.Language = "ru";
            GMap1.enableHookMouseWheelToZoom = true;
            GMap1.BackColor = Color.White;

            GMap1.addGMapUI(new GMapUI());

            GMapUIOptions options = new GMapUIOptions();

            options.maptypes_hybrid = false;
            options.keyboard = true;
            options.maptypes_physical = false;
            options.zoom_scrollwheel = true;
            GMap1.Add(new GMapUI(options));
        }



        protected string GMap1_Click(object s, GAjaxServerEventArgs e)
        {
            // Задаем настройки для метки
            GMarkerOptions mkrOpts = new GMarkerOptions();
            // Разрешаем перемещать метку
            mkrOpts.draggable = true;

            GMarker marker = new GMarker(e.point, mkrOpts);
            Router router = new Router();
            router.ip = "";
            router.x = Decimal.Parse(marker.point.lng.ToString());
            router.y = Decimal.Parse(marker.point.lat.ToString());

            long id = (long)this.Context.Session["project1"];
            router.projectId = id;

            GLatLng myPoint = new GLatLng(marker.point.lng, marker.point.lat);
            Session["point"] = myPoint;

            // Добавить метку в БД
            routerCtrl.RouterCreate(router);

            GInfoWindow window = new GInfoWindow(marker,
                string.Format(@"
                        <a href=Router/RouterTest>Проверить<a><br/><br/>
                        <a href=Router/AllRoutersTest>Проверить всё<a><br/><br/>                        
                        <a href=Router/RouterDelete>Удалить</a><br/>
                        <a href=Router/RouterEdit>Редактировать</a>")
                // сразу отображаем
            , true
            );
            return window.ToString(e.map);
        }

        protected string GMap1_MoveEnd(object s, GAjaxServerEventArgs e)
        {
            long id = (long)this.Context.Session["project1"];
            ProjectController projectCtrl = new ProjectController();
            Project project = new Project();
            project.x = Decimal.Parse(e.point.lat.ToString());
            project.y = Decimal.Parse(e.point.lng.ToString());
            project.id = id;

            projectCtrl.UpdatePosition(project);

            e.point.ToString();
            return string.Empty;
        }

        protected string GMap1_ZoomEnd(object s, GAjaxServerEventZoomArgs e)
        {
            long id = (long)this.Context.Session["project1"];
            ProjectController projectCtrl = new ProjectController();
            Project project = new Project();
            project.zoom = e.newLevel;
            project.id = id;

            projectCtrl.UpdateZoom(project);

            e.point.ToString();
            return string.Empty;
        }
    }
}